/**
 * Created by xuan on 15/12/4.
 */
/**
 * 客户跟进
 */
define(function (require) {
    'use strict';
    var angular = require('angular');
    var _ = require('underscore');
    var util = require('util');
    var ui = require('ui');

    angular.module('cstAssignApp.services', [])
        .factory('cstAssignService', ['$http', function ($http) {
            function httpGet(url, data) {
                url = '/api/index.php?r=' + url;
                return $http.get(url, {params: data})
                    .then(function (res) {
                        return res.data.data;
                    });
            }

            function httpPost(url, data) {
                url = '/api/index.php?r=' + url;
                return $http.post(url, $.param(data), {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                    .then(function (res) {
                        return res.data.data;
                    });
            }

            function getUrl(url) {
                var urlPre = 'ydxs/cst-assign/';
                return urlPre + url;
            }

            return {
                getProjectList: function (data) {
                    return httpGet('ydxs/project/list', data);
                },
                /**
                 * 逾期客户列表
                 * @param data {}
                 * proj_id    是    项目id
                 * page_index    否    页号，从1开始
                 * page_size    否    每页记录数，默认为10
                 * sort_field    否    排序字段，默认为last_date 最近跟进日期。
                 * sort_order    否    排序方向，默认为desc，倒序。asc为升序。
                 * 查询参数
                 * cst_name    否    客户名称
                 * mobile_tel    否    客户手机号码
                 * user_id    否    业务员user_id
                 * user_id_old    否    原业务员user_id
                 * follow_level    否    意向级别，多个值以逗号分隔，如：2,3,5
                 * stage_id    否    客户状态，多个值以逗号分隔，如3,5,6
                 * recover_type    否    回收类型，1：逾期客户自动回收；2：无效客户自动回收；3：离职销售员客户自动回收；4：到期未认购客户自动回收；5：其他。
                 * created_on_start    否    创建时间开始值
                 * created_on_end    否    创建时间结束值
                 * last_date_start    否    最近跟进时间开始值
                 * last_date_end    否    最近跟进时间结束值
                 * overdue_day_start    否    逾期天数开始值
                 * overdue_day_end    否    逾期天数结束值
                 * @returns {*}
                 */
                getOverDueList: function (data) {
                    var url = getUrl('get-overdue-list');
                    return httpGet(url, data);
                },
                /**
                 * 无效客户列表
                 * @param data {}
                 * @see getOverDueList
                 * @returns {*}
                 */
                getLoseList: function (data) {
                    var url = getUrl('get-lose-list');
                    return httpGet(url, data);
                },
                /**
                 * 跟进中客户列表
                 * @param data {}
                 * @see getOverDueList
                 * @returns {*}
                 */
                getFollowingList: function (data) {
                    var url = getUrl('get-following-list');
                    return httpGet(url, data);
                },
                /**
                 * 公共客户列表
                 * @param data
                 * @see getOverDueList
                 * @returns {*}
                 */
                getPublicList: function (data) {
                    var url = getUrl('get-public-list');
                    return httpGet(url, data);
                },
                /**
                 * 垃圾箱客户列表
                 * @param data
                 * @see getOverDueList
                 * @returns {*}
                 */
                getRubbishList: function (data) {
                    var url = getUrl('get-rubbish-list');
                    return httpGet(url, data);
                },
                /**
                 * 客户状态字典
                 * @param data
                 * proj_id 项目id
                 * @returns {*}
                 */
                getStageList: function (data) {
                    var url = getUrl('get-stage-list');
                    return httpGet(url, data);
                },
                /**
                 * 意向级别字典
                 * @param data
                 * proj_id 项目id
                 * @returns {*}
                 */
                getFollowlevelList: function (data) {
                    var url = getUrl('get-followlevel-list');
                    return httpGet(url, data);
                },
                /**
                 * 查看客户信息
                 * 返回值中只有s_broker2customerId 有值时，才显示：broker_name、yykf_date、cst_detail 这几个字段的值。
                 * @param data
                 * proj_id 项目id
                 * cst_id 客户id
                 * @returns {*}
                 */
                getCstInfo: function (data) {
                    var url = getUrl('get-cst-info');
                    return httpGet(url, data);
                },
                /**
                 * 查询客户变更记录列表
                 * @param data
                 * cst_id 客户id
                 * page_index 页号，从1开始
                 * page_size 每页记录数，默认值10
                 * @returns {*}
                 */
                getCstModifyList: function (data) {
                    var url = getUrl('get-cst-modify-list');
                    return httpGet(url, data);
                },
                /**
                 * 客户分配日志列表
                 * @param data
                 * proj_id    是    项目id
                 * cst_id    是    客户id
                 * page_index    否    页号，从1开始
                 * page_size    否    每页记录数，默认值10
                 * @returns {*}
                 */
                getAssignLogList: function (data) {
                    var url = getUrl('get-assign-log-list');
                    return httpGet(url, data);
                },
                /**
                 * 客户回收日志列表
                 * @param data
                 * proj_id    是    项目id
                 * cst_id    是    客户id
                 * page_index    否    页号，从1开始
                 * page_size    否    每页记录数，默认值10
                 * @returns {*}
                 */
                getRecoverLogList: function (data) {
                    var url = getUrl('get-recover-log-list');
                    return httpGet(url, data);
                },
                /**
                 * 获取销售员列表
                 * @param data
                 * proj_id    是    项目id
                 * page_index    否    页号，从1开始
                 * page_size    否    每页大小，默认10
                 * search_key    否    查询条件（姓名或电话）
                 * @returns {*}
                 */
                getSalerList: function (data) {
                    var url = getUrl('get-saler-list');
                    return httpGet(url, data);
                },
                getAllSalerList: function (data) {
                    var url = 'ydxs/genjin-mng/get-saler-list';
                    return httpGet(url, data);
                },
                /**
                 * 分配客户|批量分配
                 * @param data
                 * proj_id    是    项目id
                 * opp_ids    是    要分配的机会id列表，前端按数组格式传递
                 * assign_to_user    是    分配给的业务员id
                 * @returns {*}
                 * {
                 *       "data": {
                 *           "suc": [
                 *               {
                 *                   "opp_id": "opp_id1",
                 *                   "retCode": "0",
                 *                   "errMsg": ""
                 *               },
                 *               {
                 *                   "opp_id": "opp_id2",
                 *                   "retCode": "0",
                 *                   "errMsg": ""
                 *               }
                 *           ],
                 *           "fail": [
                 *               {
                 *                   "opp_id": "opp_id3",
                 *                   "retCode": "ret_code1",
                 *                   "errMsg": "errMsg1"
                 *               },
                 *               {
                 *                   "opp_id": "opp_id4",
                 *                   "retCode": "ret_code2",
                 *                   "errMsg": "errMsg2"
                 *               }
                 *           ]
                 *       },
                 *       "retCode": "xxxxx",
                 *       "retMsg": "xxxxxxxx"
                 *   }
                 */
                assignCustomer: function (data) {
                    var url = getUrl('assign-customer');
                    return httpPost(url, data);
                },
                /**
                 * 分配所有客户
                 * @param data
                 * proj_id    是    项目id
                 * view_type    是    视图类型，1：逾期客户、2：无效客户、3：跟进中客户、4：公共客户、5：垃圾箱客户
                 * assign_to_user    是    分配给的业务员id
                 * cst_name    否    客户名称
                 * 其他查询条件参考 @see getOverDueList
                 * @returns {*} @see assignCustomer
                 */
                assignAllCustomer: function (data) {
                    var url = getUrl('assign-all-customer');
                    return httpPost(url, data);
                },
                /**
                 * 回收客户|批量回收
                 * @param data
                 * proj_id    是    项目id
                 * opp_ids    是    要回收的机会id列表，前端按数组格式传递
                 * recover_reason    是    回收原因
                 * @returns {*} @see assignCustomer
                 */
                recoverCustomer: function (data) {
                    var url = getUrl('recover-customer');
                    return httpPost(url, data);
                },
                /**
                 * 回收所有客户
                 * @param data
                 * proj_id    是    项目id
                 * view_type    是    视图类型，1：逾期客户、2：无效客户、3：跟进中客户、4：公共客户、5：垃圾箱客户
                 * recover_reason    是    回收原因
                 * 其他查询条件参考 @see getOverDueList
                 * @returns {*} @see assignCustomer
                 */
                recoverAllCustomer: function (data) {
                    var url = getUrl('recover-all-customer');
                    return httpPost(url, data);
                },
                /**
                 * 公共客户自动分配
                 * @param data
                 * proj_id    是    项目id
                 * 其他查询条件参考 @see getOverDueList
                 * @returns {*} @see assignCustomer
                 */
                autoAssignPublicCst: function (data) {
                    var url = getUrl('auto-assign-public-cst');
                    return httpPost(url, data);
                },
                /**
                 * 移动公共客户到垃圾箱
                 * @param data
                 * opp_ids    是    要移动的客户机会id，前端传递数组格式，如：['39cb4c31-2ca9-6434-a779-08216e0b970d','39cb4c31-2cb7-446d-72f5-bd7268f42e8e']
                 * @returns {*}
                 */
                moveToRubbish: function (data) {
                    var url = getUrl('move-to-rubbish');
                    return httpPost(url, data);
                },
                /**
                 * 垃圾箱客户回收|批量回收
                 * @param data
                 * opp_ids    是    要回收的机会id列表，前端按数组格式传递
                 * proj_id    是    项目id
                 * @returns {*}
                 */
                recoverRubbishCst: function (data) {
                    var url = getUrl('recover-rubbish-cst');
                    return httpPost(url, data);
                },
                /**
                 * 导出客户资料
                 * @param data
                 * "view_no"："1" // 逾期：1，无效：2，跟进中：3，公共客户：4
                 * @returns {*}
                 */
                export: function (data) {
                    var url = getUrl('export');
                    return httpGet(url, data);
                },
                /**
                 * 自动分配
                 * @param data
                 */
                autoAssignPublic: function (data) {
                    var url = getUrl('auto-assign-public-cst');
                    return httpPost(url, data);
                },
                /**
                 * 垃圾箱客户回收|批量回收
                 * @param data
                 * @returns {*}
                 */
                recoverRubbishCustomer: function (data) {
                    var url = getUrl('recover-rubbish-cst');
                    return httpPost(url, data);
                },
                /**
                 * 检测项目是否绑定了ERP项目
                 * @param data
                 * @returns {*}
                 */
                checkHasBindErp: function (data) {
                    var url = 'common/project/check-has-bind-erp';
                    return httpGet(url, data);
                },
                /**
                 * 获取客户信息及以多客户联系电话列表
                 * @param data
                 * @returns {*}
                 */
                getCstCommsList: function (data) {
                    var url = getUrl('get-cst-comms-list');
                    return httpGet(url, data);
                },
                /**
                 * 保存客户联系电话及状态
                 * @param data
                 * @returns {*}
                 */
                saveCstInfo: function (data) {
                    var url = getUrl('save-cst-info');
                    return httpPost(url, data);
                },
                /**
                 * 批量修改客户状态
                 * @param data
                 * @returns {*}
                 */
                bulkChangeStageId: function (data) {
                    var url = getUrl('bulk-change-stage-id');
                    return httpPost(url, data);
                },
                /**
                 * 检测电话号码是否已存在
                 * @param data
                 * @returns {*}
                 */
                checkTelIsExist: function (data) {
                    var url = getUrl('check-tel-is-exist');
                    return httpGet(url, data);
                }
            };
        }])
        .factory('cstInfoService', ['cstAssignService', 'PAGE_SIZE', function (cstAssignService, PAGE_SIZE) {
            return {
                init: function (proj_id, cst_id, $dialogScope) {
                    $dialogScope.tabs = {
                        'cstInfo': {
                            page_index: 1,
                            page_size: PAGE_SIZE,
                            init: function () {
                                $dialogScope.getCstInfo();
                            }
                        },
                        'cstModifyList': {
                            page_index: 1,
                            page_size: PAGE_SIZE,
                            init: function () {
                                $dialogScope.query.sort_field = 'CreatedOn';
                                $dialogScope.getCstModifyList();
                            }
                        },
                        'assignLogList': {
                            page_index: 1,
                            page_size: PAGE_SIZE,
                            init: function () {
                                $dialogScope.getAssignLogList();
                            }
                        },
                        'recoverLogList': {
                            page_index: 1,
                            page_size: PAGE_SIZE,
                            init: function () {
                                $dialogScope.getRecoverLogList();
                            }
                        }
                    };
                    $dialogScope.$watch('tab', function (newvalue, oldValue) {
                        if (newvalue !== oldValue) {
                            $dialogScope.query = {
                                sort_order: 'desc',
                                sort_field: 'fp_date'
                            };
                            var tab = $dialogScope.tabs[newvalue];
                            tab && tab.init();
                        }
                    });
                    $dialogScope.getCstInfo = function () {
                        cstAssignService
                            .getCstInfo({cst_id: cst_id, proj_id: proj_id})
                            .then(function (data) {
                                $dialogScope.cstInfo = data;
                            });
                    };
                    $dialogScope.getList = function (page_index, objProp, serviceMethod) {
                        page_index || (page_index = 1);
                        $dialogScope.tabs[objProp].page_index = page_index;
                        cstAssignService[serviceMethod]({
                            cst_id: cst_id,
                            proj_id: proj_id,
                            page_index: page_index,
                            page_size: $dialogScope.tabs[objProp].page_size,
                            sort_order: $dialogScope.query.sort_order,
                            sort_field: $dialogScope.query.sort_field
                        })
                            .then(function (data) {
                                $dialogScope.tabs[objProp].list = data.list;
                                $dialogScope.tabs[objProp].total = data.total;
                            });
                    };
                    $dialogScope.getCstModifyList = function (page_index) {
                        $dialogScope.getList(page_index, 'cstModifyList', 'getCstModifyList');
                    };
                    $dialogScope.getAssignLogList = function (page_index) {
                        $dialogScope.getList(page_index, 'assignLogList', 'getAssignLogList');
                    };
                    $dialogScope.getRecoverLogList = function (page_index) {
                        $dialogScope.getList(page_index, 'recoverLogList', 'getRecoverLogList');
                    };

                    // init
                    $dialogScope.tab = 'cstInfo';
                    $dialogScope.tabs[$dialogScope.tab].init();
                }
            };
        }])
        .factory('editCstInfoService', ['cstAssignService', function (cstAssignService) {
            return {
                init: function (proj_id, cst_id, $dialogScope, hasBindErp) {
                    $dialogScope.hasBindErp = hasBindErp;
                    $dialogScope.delConfirm = function(comms_list, $index){
                        util.confirm('确实要删除该联系方式吗？',{
                            ok: function(){
                                $dialogScope.$apply(function(){
                                    comms_list.splice($index,1);
                                });
                            }
                        });
                    };
                    $dialogScope.getCstCommsList = function () {
                        cstAssignService
                            .getCstCommsList({cst_id: cst_id, proj_id: proj_id})
                            .then(function (data) {
                                $dialogScope.cst_info = data.cst_info;
                                $dialogScope.stage_id = $dialogScope.cst_info.stage_id;
                                $dialogScope.comms_list = data.comms_list;

                                _.each($dialogScope.comms_list, function (comms) {
                                    comms.comms_no_pre = comms.comms_no;
                                });
                                $dialogScope.stageList = [];
                                if ($dialogScope.stage_id === '0') {
                                    if ($dialogScope.cst_info.is_exist_lfgj !== true) {
                                        $dialogScope.stageList.push({id: 2, text: '问询'});
                                    }
                                    $dialogScope.stageList.push({id: 0, text: '无效'});
                                    $dialogScope.stageList.push({id: 3, text: '看房'});
                                } else if ($dialogScope.stage_id === '2') {
                                    $dialogScope.stageList.push({id: 2, text: '问询'});
                                } else {
                                    $dialogScope.stageList.push({id: 3, text: '看房'});
                                }
                                $dialogScope.stageList = $dialogScope.stageList.concat([
                                    {id: 4, text: '认筹'},
                                    {id: 5, text: '认购'},
                                    {id: 6, text: '签约'}
                                ]);
                            });
                    };
                    $dialogScope.getCstCommsList();
                },
                save: function (proj_id, cst_id, opp_id, $dialogScope,$dialog, callback) {
                    var data = {
                        proj_id: proj_id,
                        cst_id: cst_id,
                        opp_id: opp_id,
                        stage_id: $dialogScope.stage_id,
                        comms_list: angular.copy($dialogScope.comms_list)
                    };
                    if ($dialogScope.stage_id === '0' || $dialogScope.hasBindErp) {
                        delete data.stage_id;
                    }
                    cstAssignService.saveCstInfo(data).then(function () {
                        $dialog.close();
                        callback && callback();
                    });
                    return false;
                }
            };
        }])
        .factory('progressService',['$rootScope','$compile','$templateRequest','cstAssignService',
            function($rootScope,$compile,$templateRequest,cstAssignService){
            return {
                init: function (method,$dialogScope, data, view_no,count,callback,title) {
                    var MAX_SIZE = 100, newScope,_dialog;
                    var needProgress = count > MAX_SIZE;
                    if(needProgress){
                        newScope = $rootScope.$new(true);
                        newScope.count = count;
                        newScope.first = 0;
                        newScope.end = MAX_SIZE;
                        newScope.percentage = 0 + '%';
                        newScope.executed = false;
                    }
                    var hasCancel = false;
                    data.view_type = view_no;
                    data.batch_count = MAX_SIZE;
                    function send() {
                        cstAssignService[method](data)
                            .then(function () {
                                if(needProgress){
                                    if((newScope.count > newScope.end) && !hasCancel){
                                        newScope.first = newScope.end;
                                        newScope.percentage = parseInt(newScope.first/newScope.count * 100) + '%';
                                        if((newScope.count - newScope.first) > MAX_SIZE){
                                            newScope.end += MAX_SIZE;
                                        }else{
                                            newScope.end = newScope.count;
                                        }
                                        send();
                                    }else{
                                        newScope.percentage = '100%';
                                        newScope.executed = true;
                                        setTimeout(function(){
                                            _dialog.close().remove();
                                        },300);
                                    }
                                }else{
                                    callback && callback();
                                }
                            });
                    }
                    if(count > MAX_SIZE){
                        $templateRequest('inc/dialog/bar.html').then(function (template) {
                            var templateElement = $compile(template)(newScope);
                            util.showDialog({
                                title: title,
                                fixed: true,
                                content: templateElement,
                                cancelValue: '取消',
                                cancelDisplay: true,
                                cancel: function () {
                                    hasCancel = true;
                                },
                                onclose: function(){
                                    setTimeout(function(){
                                        newScope.$destroy();
                                        templateElement.remove();
                                        callback && callback();
                                    },0);
                                },
                                onshow: function(){
                                    _dialog = this;
                                    send();
                                }
                            });
                        });
                    }else{
                        send();
                    }
                }
            };
        }])
        .factory('assignCustomerService', ['progressService','cstAssignService', 'PAGE_SIZE',
            function (progressService,cstAssignService, PAGE_SIZE) {
            return {
                init: function (proj_id, $dialogScope) {
                    $dialogScope.query = {
                        page_index: 1,
                        page_size: PAGE_SIZE
                    };
                    $dialogScope.getSalerList = function (page_index) {
                        page_index || (page_index = 1);
                        $dialogScope.query.page_index = page_index;
                        cstAssignService
                            .getSalerList({
                                proj_id: proj_id,
                                page_index: page_index,
                                page_size: $dialogScope.query.page_size,
                                search_key: $dialogScope.keyword
                            })
                            .then(function (data) {
                                $dialogScope.salerList = data.list;
                                $dialogScope.total = data.total;
                            });
                    };
                    $dialogScope.selectUser = function (user) {
                        $dialogScope.select_user = user;
                    };
                    // init
                    $dialogScope.getSalerList();
                },
                checkAssign: function ($dialogScope) {
                    if (!$dialogScope.select_user) {
                        util.alert('请选择要分配的销售员!');
                        return false;
                    }
                    return true;
                },
                assignCustomer: function (proj_id, cst_id_arr, $dialogScope, callback) {
                    if (!this.checkAssign($dialogScope)) {
                        return false;
                    }
                    cstAssignService
                        .assignCustomer({
                            proj_id: proj_id,
                            opp_ids: [].concat(cst_id_arr),
                            assign_to_user: $dialogScope.select_user.s_userId
                        })
                        .then(function (data) {
                            var values = _.values(data.fail);
                            var sucArr = _.values(data.suc) || [];
                            if (_.isObject(data.fail) && values.length > 0  ) {
                                util.alert('<p>成功' + sucArr.length + '条，失败' + values.length + '条</p><p>' + _.first(values).errMsg + '</p>');
                            } else {
                                ui.showSucTip('分配成功！');
                            }
                            callback && callback();
                        });
                },
                assignCountCustomer: function ($dialogScope, data, view_no,count,callback) {
                    data.assign_to_user = $dialogScope.select_user.s_userId;
                    progressService.init('assignAllCustomer',$dialogScope, data, view_no,count,callback,'客户分配');
                },
                assignAllCustomer: function (curProjectId, list, $dialogScope, callback, checkCountAll, queryData, view_no,count) {
                    if (!this.checkAssign($dialogScope)) {
                        return false;
                    }
                    if (checkCountAll) {
                        this.assignCountCustomer($dialogScope, queryData, view_no,count,callback);
                    } else {
                        this.assignCustomer(curProjectId, _.map(list, 'opp_id'), $dialogScope, callback);
                    }
                }
            };
        }])
        .factory('recoverCustomerService', ['progressService','cstAssignService', function (progressService,cstAssignService) {
            return {
                init: function (customer) {
                    var stage_id = customer.stage_id;
                    if (stage_id === '5' || stage_id === '6') {
                        util.alert('当前客户已成交，不允许回收');
                        return false;
                    }
                },
                initAll: function (list, $dialogScope,checkCountAll,total) {
                    if(checkCountAll){
                        $dialogScope.checkSize = total;
                    }else{
                        $dialogScope.checkSize = list.length;
                    }
                },
                recoverCustomer: function (proj_id, cst_id_arr, $dialogScope, callback) {
                    cstAssignService.recoverCustomer({
                        proj_id: proj_id,
                        recover_reason: $dialogScope.recover_reason,
                        opp_ids: [].concat(cst_id_arr)
                    }).then(function () {
                        callback && callback();
                    });
                },
                recoverCountCustomer: function ($dialogScope, data, view_no,count,callback) {
                    data.recover_reason = $dialogScope.recover_reason;
                    progressService.init('recoverAllCustomer',$dialogScope, data, view_no,count,callback,'客户回收');
                },
                recoverAllCustomer: function (curProjectId, list, $dialogScope, callback, checkCountAll, queryData, view_no,count) {
                    if (checkCountAll) {
                        this.recoverCountCustomer($dialogScope, queryData, view_no,count,callback);
                    } else {
                        this.recoverCustomer(curProjectId, _.map(list, 'opp_id'), $dialogScope, callback);
                    }
                },
                recoverRubbishCustomer: function (proj_id, cst_id_arr, callback) {
                    util.confirm('确定要将选择的客户重新回收为公共客户吗？', {
                        ok: function () {
                            cstAssignService.recoverRubbishCustomer({
                                proj_id: proj_id,
                                opp_ids: [].concat(cst_id_arr)
                            }).then(function (data) {
                                if (data.fail && data.fail.length > 0) {
                                    util.alert(_.map(data.fail, 'errMsg').join(','));
                                } else {
                                    ui.showSucTip('回收成功！');
                                }
                                callback && callback();
                            });
                        }
                    });

                },
                recoverRubbishAllCustomer: function (curProjectId, list, callback) {
                    if (list.length > 0) {
                        this.recoverRubbishCustomer(curProjectId, _.map(list, 'opp_id'), callback);
                    } else {
                        util.alert('请选择客户。');
                    }
                }
            };
        }]);
});
